package bitcat.chuenyee.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.Watcher;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.SimpleFtpServer;
import cn.hutool.log.StaticLog;
import cn.hutool.socket.aio.AioClient;
import cn.hutool.socket.aio.AioServer;
import cn.hutool.socket.aio.AioSession;
import cn.hutool.socket.aio.SimpleIoAction;
import org.apache.ftpserver.usermanager.impl.BaseUser;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author chuenyee
 * @since 2021/11/5 17:25
 */
public class SocketUntil {
    static AioClient client;
    static AioServer aioServer;

    /**
     * 异步socket服务端
     */
    public static void aioServerStart(int port) {
        aioServer = new AioServer(port);
        aioServer.setIoAction(new SimpleIoAction() {

            @Override
            public void accept(AioSession session) {
                StaticLog.debug("【客户端】：{} 连接。", session.getRemoteAddress());
                session.write(BufferUtil.createUtf8("=== Welcome to Hutool socket server. ==="));
            }

            @Override
            public void doAction(AioSession session, ByteBuffer data) {
                Console.log("doAction");
                Console.log(data);
                if (false == data.hasRemaining()) {
                    StringBuilder response = StrUtil.builder()//
                            .append("HTTP/1.1 200 OK\r\n")//
                            .append("Date: ").append(DateUtil.formatHttpDate(DateUtil.date())).append("\r\n")//
                            .append("Content-Type: text/html; charset=UTF-8\r\n")//
                            .append("\r\n")
                            .append("Hello Hutool socket");//
                    Console.log("close");
                    session.writeAndClose(BufferUtil.createUtf8(response));
//                    session.write(BufferUtil.createUtf8(response));
                } else {
                    Console.log("read");
                    session.read();
                }
            }
        }).start(true);
    }

    /**
     * 异步socket客户端
     */
    public static void aioClientStart(String hostname, int port) {
        client = new AioClient(new InetSocketAddress(hostname, port), new SimpleIoAction() {
            @Override
            public void doAction(AioSession session, ByteBuffer data) {
                if (data.hasRemaining()) {
                    Console.log("客户端接收消息");
                    Console.log(StrUtil.utf8Str(data));
                    session.read();
                }
                Console.log("OK");
            }
        });
        client.read();
//        client.close();
        Console.log("客户端关闭");
    }

    public static AioClient getClient() {
        return client;
    }

    public static AioServer getAioServer() {
        return aioServer;
    }

    public static void sendMsg(String msg) {
        ByteBuffer byteBuffer = StringUntils.getByteBuffer(msg);
        SocketUntil.getClient().write(byteBuffer);
    }

    /**
     * <p>
     *
     * </p>
     *
     * @author chuenyee
     * @since 2021/10/22 11:32
     */
    public static class FileUtil {

        /**
         * 本地监听
         */
        public void listener(String path, Watcher watcher, int maxDepth) {
            File file = cn.hutool.core.io.FileUtil.file(path);
            WatchMonitor watchMonitor = WatchMonitor.createAll(file, watcher);

            //设置监听目录的最大深入，目录层级大于制定层级的变更将不被监听，默认只监听当前层级目录
            watchMonitor.setMaxDepth(maxDepth);
            //启动监听
            watchMonitor.start();
        }

        /**
         * 开启匿名ftp
         */
        public static void ftpServerStart(String path) {
            SimpleFtpServer
                    .create()
                    // 此目录必须存在
                    .addAnonymous(path)
                    .start();
        }

        /**
         * 开启自定义用户FTP
         */
        public static void ftpServerStart(String path, String username, String password) {
            BaseUser user = new BaseUser();
            user.setName(username);
            user.setPassword(password);
            user.setHomeDirectory(path);
            SimpleFtpServer
                    .create()
                    .addUser(user)
                    .start();
        }

        public static FtpClient FtpClientCreate(String host) {
            FtpClient ftpClient = new FtpClient(host);
            return ftpClient;
        }

        public static class FtpClient {
            Ftp ftp;

            FtpClient(String host) {
                ftp = new Ftp(host);
            }

            public void ftpUpload(String directory, String destPath, String path) {
                //匿名登录（无需帐号密码的FTP服务器）
                ftp.cd(directory);
                //上传本地文件
                ftp.upload(destPath, cn.hutool.core.io.FileUtil.file(path));

                //关闭连接
                try {
                    ftp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            public void ftpDownload(String path, String fileName, String downloadPath) {
                //下载远程文件
                ftp.download(path, fileName, cn.hutool.core.io.FileUtil.file(downloadPath));

                //关闭连接
                try {
                    ftp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            public List<String> ftpls(String path) {
                //下载远程文件
                List<String> ls = ftp.ls(path);
                return ls;
            }

            public void close() {
                try {
                    ftp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
